// 引入加密
const md5 = require("md5")
// 引入数据库
const {
  mysqlFun
} = require('../mysql/mysql');
// 导出注册方法
exports.postRight = function (app) {
  // 判断账号是否存在
  app.post('/rightIsUseerName', (req, res) => {
    const sql = `select * from userdata where user =${req.body.user}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        res.json({
          code: 'C0005',
          msg: '用户名已被注册'
        })
      }
    }
    mysqlFun(sql, obj);
  })

  // 判断邮箱是否存在
  // rightIsEmail
  app.post('/rightIsEmail', (req, res) => {
    const sql = `select * from userdata where email ='${req.body.email}'`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        res.json({
          code: 'C0006',
          msg: '邮箱已被注册'
        })
      } else {
        res.json({
          code: 'C0007',
          msg: '邮箱未注册'
        })
      }
    }
    mysqlFun(sql, obj);
  })

  // 添加账号
  app.post("/right", (req, res) => {
    // 向数据库添加账号
    const sql = `INSERT INTO userdata(user,password,email,sex,time) value ('${req.body.user}','${md5(req.body.password)}','${req.body.email}','${req.body.sex}','${(new Date()).getTime()}')`;

    // 引入数据库函数
    function obj() {
      res.json({
        code: 'C0003',
        msg: '创建成功'
      })
    }
    mysqlFun(sql, obj);
  })
}